package com.laoye.service.impl;

import com.laoye.Exception.exception.BaseException;
import com.laoye.annotation.Log;
import com.laoye.bean.Address;
import com.laoye.mapper.AddressMapper;
import com.laoye.service.AddressService;
import com.laoye.util.ThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Transactional
    @CacheEvict(value = {"addressList", "defaultAddress"},
            key = "'user:' + T(com.laoye.util.ThreadLocal).getCurrentId()")
    @Override
    @Log("用户新增地址")
    public void addAddress(Address address) {
        if (address==null){
            throw new BaseException(401,"请填写完整的地址信息");
        }
        if (address.getIs_default()==1){
            addressMapper.cancelDefault(ThreadLocal.getCurrentId());  //当添加了默认地址，则取消其他默认地址
        }
        address.setUser_id(ThreadLocal.getCurrentId());
       addressMapper.addAddress(address);
    }

    @Cacheable(value = "addressList",
            key = "'user:' + T(com.laoye.util.ThreadLocal).getCurrentId()",
            unless = "#result == null")
    @Override
    public List<Address> addressList() {
        return addressMapper.addressList(ThreadLocal.getCurrentId());
    }


    @Cacheable(value = "defaultAddress",
            key = "'user:' + T(com.laoye.util.ThreadLocal).getCurrentId()",
            unless = "#result == null")
    @Override
    public Address getAddress() {      //获取默认地址
        return addressMapper.getAddress(ThreadLocal.getCurrentId());
    }


    @Transactional
    @CacheEvict(value = {"addressList", "defaultAddress"},
            key = "'user:' + T(com.laoye.util.ThreadLocal).getCurrentId()")
    @Override
    @Log("用户修改地址")
    public void editAddress(Address address) {
        if (address==null||address.getId()==null){
            throw new BaseException(401,"地址信息不存在");
        }
        if (address.getIs_default()==1){
            addressMapper.cancelDefault(ThreadLocal.getCurrentId());
        }
       addressMapper.editAddress(address);
    }



    @Transactional
    @CacheEvict(value = {"addressList", "defaultAddress"},
            key = "'user:' + T(com.laoye.util.ThreadLocal).getCurrentId()")
    @Override
    @Log("用户删除地址")
    public void deleteAddress(Integer id) {
        if (id==null){
            throw new BaseException(401,"用户ID不存在");
        }
        addressMapper.deleteAddress(id);
    }

}
